<template>
  <div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th>
            <input type="checkbox" @change="change" :checked="isAll" />
            <span>全选</span>
          </th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in list" :key="item.name">
          <td>
            <input type="checkbox" v-model="item.checked" />
          </td>
          <td>{{ item.name }}</td>
          <td>{{ item.price }}</td>
          <td>
            <button @click="sub(index)">-</button>
            {{ item.num }}
            <button @click="add(index)">+</button>
          </td>
          <td>
            {{ total(index) }}
          </td>
          <td>
            <button @click="del(index)">删除</button>
          </td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td>合计:</td>
          <td colspan="5">
            {{ totalPrice }}
          </td>
        </tr>
      </tfoot>
    </table>
    <div>
      名称：<input type="text" v-model.trim="form.name" />
      价格:<input type="number" v-model="form.price" />
      数量:<input type="number" v-model="form.num" />
      <button @click="addBtn">添加</button>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations, mapGetters } from 'vuex'
export default {
  data () {
    return {
      list: this.$store.state.goodList,
      form: {
        name: '',
        price: '',
        num: '',
        checked: false
      }
    }
  },

  created () {},
  computed: {
    ...mapState(['goodList']),
    ...mapGetters(['total', 'isAll', 'totalPrice'])
  },
  methods: {
    ...mapMutations(['addNum', 'subNum', 'delList', 'ChangeInput', 'addList']),

    add (index) {
      this.addNum(index)
    },
    sub (index) {
      this.subNum(index)
    },
    del (index) {
      this.delList(index)
    },
    change () {
      this.ChangeInput(!this.isAll)
    },
    addBtn () {
      this.addList(JSON.parse(JSON.stringify(this.form)))
      this.form.name = ''
      this.form.price = ''
      this.form.num = ''
    }
  }
}
</script>

<style scoped lang="less">
.a {
  width: 555px;
  height: 1rem;
  background-color: pink;
}
</style>
